package cn.thornbird.orgsync.repository.specification;

import cn.thornbird.orgsync.entity.VerificationCode;
import cn.thornbird.orgsync.entity.status.VerificationCodeUsage;
import cn.thornbird.orgsync.vo.request.VerificationCodeQueryRequest;
import lombok.AllArgsConstructor;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@AllArgsConstructor
public class VerificationCodeSpecification extends BaseSpecification<VerificationCode> {

    private static final long serialVersionUID = -1404071438847251509L;

    private final VerificationCodeQueryRequest verificationCodeQueryRequest;

    @Override
    public Predicate toPredicate(Root<VerificationCode> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = new ArrayList<>();
        String mobile = verificationCodeQueryRequest.getMobile();
        VerificationCodeUsage usage = verificationCodeQueryRequest.getUsage();
        Boolean success = verificationCodeQueryRequest.getSuccess();
        Boolean used = verificationCodeQueryRequest.getUsed();
        Date startDate = verificationCodeQueryRequest.getStartDate();
        Date endDate = verificationCodeQueryRequest.getEndDate();
        predicates.add(toKeywordPredicate(mobile, Arrays.asList("mobile"), root, criteriaBuilder));
        if (usage != null) {
            predicates.add(criteriaBuilder.equal(root.get("usage"), usage));
        }
        predicates.add(createEqualPredicate(root, criteriaBuilder, "success", success));
        predicates.add(createEqualPredicate(root, criteriaBuilder, "used", used));
        predicates.add(createDatePredicates(root, criteriaBuilder, "createdAt", startDate, endDate));
        return toPredicate(criteriaBuilder, predicates);
    }

}
